<?php
require_once ('AppModel.php');
require_once ('../../lib/phpqrcode/qrlib.php');



/**
 * @author Windows 8 Pro User
 * @version 1.0
 * @created 02-dez-2013 23:26:30
 */
class User extends AppModel {

	/**
	 * Set the model name
	 */
	public $name = 'User';
	/**
	 * Set the model relationship
	 */
	public $hasAndBelongsToMany = 'Establishment';
	/**
	 * Set the model validation
	 */
	public $validate = array(
		'username' => array(
			'required' => array(
				'rule' => array('notEmpty'),
				'message' => 'Login requerido'
			)
		),
		'password' => array(
			'required' => array(
				'rule' => array('notEmpty'),
				'message' => 'Senha requerida'
			)
		),
		'role' => array(
			'valid' => array(
				'rule' => array('inList', array('adm', 'usr')),
				'message' => 'Por favor esconha um acesso válido',
				'allowEmpty' => false
			)
		),												
		'email' => array(
			'required' => array(
				'rule' => array('email'),
				'message' => 'Por favor digite um e-mail válido',
			)
		)
	);

	/**
	 * 
	 * @param options    The provided options before save
	 */
	public function beforeSave($options = array()) {
		// Encrypt the password
		$this->encryptPassword();
		
		// Generate the QRCode
		$this->generateQRCode();
		
		// Provide the return
		return true;
	}
	
	private function encryptPassword() {
		// Get the password before it saves
		if (isset($this->data[$this->alias]['password'])) {
			// Encrypt the password
			$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
		}
	}
	
	private function generateQRCode() {
		// Contents of the qrcode
		$contents = $this->data[$this->alias]['username'];				
	
		// Set the absolute path
		$pngAbsoluteFilePath = IMAGES . 'qrcode/' . String::uuid() . '.png';
			
		// Check if the file exists
		if (!(file_exists($pngAbsoluteFilePath))) {
			// Generate the file
			QRcode::png($contents, $pngAbsoluteFilePath);
				
			// Save the blob
			$this->data[$this->alias]['qrcode'] = base64_encode(file_get_contents($pngAbsoluteFilePath));
	
			// Delete the file
			unlink($pngAbsoluteFilePath);
		}
	}

}
?>